<template>
    <div class="app-container">
        <h1 class="title">发布课程</h1>
        <el-steps :active="1" align-center style="margin-bottom: 40px" process-status="wait" >
            <el-step title="填写课程基本信息"></el-step>
            <el-step title="创建课程大纲"></el-step>
            <el-step title="发布课程"></el-step>
        </el-steps>

        <el-form :model="courseAdd" ref="courseForm" label-width="120px" style="margin-top:30px" :rules="rules">
            <el-form-item label="课程标题" prop="title">
                <el-input v-model="courseAdd.title" placeholder="示例:机器学习项目课:从基础到搭建项目视频课程。专业名称注意大小写"></el-input>
            </el-form-item>
            <el-form-item label="课程类别" prop="subjectId">
                <el-select v-model="courseAdd.subjectParentId" placeholder="请选择" @change="subjectLevelOneChange">
                    <el-option v-for="item in subjectNestedList" :key="item.id" :label="item.title" :value="item.id">
                    </el-option>
                </el-select>
                <el-select v-model="courseAdd.subjectId" placeholder="请选择">
                    <el-option v-for="item in subsubjectList" :key="item.id" :label="item.title" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="课程讲师" prop="teacherId">
                <el-select v-model="courseAdd.teacherId" placeholder="请选择">
                    <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="总课时" prop="lessonNum">
                <el-input-number v-model="courseAdd.lessonNum" controls-position="right" :min="1">
                </el-input-number>
            </el-form-item>
            <el-form-item label="课程简介">
                <Tinymce v-model="courseAdd.description"></Tinymce>
            </el-form-item>
            <el-form-item label="课程封面">
                <el-upload class="upload-demo" ref="upload" :limit="1" :action="`${BASE_URL}/file/upload?host=cover`"
                    :before-upload="beforeCoverUpload" :show-file-list="false" :on-success="coverUploadSuccess">
                    <img :src="courseAdd.cover">
                </el-upload>
            </el-form-item>
            <el-form-item label="课程价格" prop="price">
                <el-input-number v-model="courseAdd.price" controls-position="right" :min="0">
                </el-input-number>元
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="next">保存并下一步</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import teacherApi from '@/api/teacher'
import courseApi from '@/api/course'
import subjectApi from '@/api/subject'
import Tinymce from '../../components/Tinymce'
export default {
    components: { Tinymce },
    data() {
        return {
            num: 0,
            courseAdd: {
                title: '',
                subjectId: '',
                subjectParentId: '',
                lessonNum: 0,
                cover: 'http://houpuyun-img.oss-cn-beijing.aliyuncs.com/20200305163327_poyes.jpeg',
                price: 0,
                description: "",
                teacherId: '',
            },
            subjectNestedList: [],//一级课程分类
            teacherList: [],//讲师数据
            subsubjectList: [],//二级课程分类
            BASE_URL: process.env.BASE_API,
            // 格式验证
            rules: {
                title: [
                    { required: true, message: '请输入课程标题', trigger: 'blur' },
                    { max: 50, message: '长度最大为50个字符', trigger: 'blur' }
                ],
                lessonNum: [
                    { required: true, message: '请输入总课时', trigger: 'blur' },
                    { type: "number", message: '总课时必须是数字', trigger: 'blur' }
                ],
                subjectId: [
                    { required: true, message: '请选择二级分类', trigger: 'change' }
                ],
                teacherId: [
                    { required: true, message: '请选择课程讲师', trigger: 'change' }
                ],
                price: [
                    { required: true, message: '请输入价格', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.init()
    },
    methods: {
        // 初始化课程分类下拉列表数据
        initSubjectList() {
            // 调用获取课程分类api
            subjectApi.getList().then(res => {
                this.subjectNestedList = res.data
            })
        },
        // 初始化讲师下拉列表数据
        initTeacherList() {
            // 调用获取课程分类api
            teacherApi.listTeacher().then(res => {
                this.teacherList = res.data
            })
        },
        next() {
            // 调用api前进行格式校验
            this.$refs["courseForm"].validate((valid) => {
                if (valid) {
                    // 验证通过
                    if (this.courseAdd.id) {
                        this.updateCourse()
                    } else {
                        this.addCourse()
                    }
                } else {
                    // 格式校验失败
                    console.log('error submit!!');
                    return false;
                }

                this.$router.push({ path: '/course/chapter' })
            })
        },
        // 一级课程分类改变时触发
        subjectLevelOneChange(value) {
            // 循环遍历yijifenlei
            for (let i = 0; i < this.subjectNestedList.length; i++) {
                // 如果当前获取到的id等于一级课程下的id
                if (this.subjectNestedList[i].id == value) {
                    // 把当前一级课程下的子集赋给二级课程
                    this.subsubjectList = this.subjectNestedList[i].children
                    // 清空查询条件中的二级分类id
                    this.courseAdd.subjectId = ''
                    return
                }
            }
        },
        // 课程封面上传之前文件校验
        beforeCoverUpload(file) {
            console.log(file);
            // 判断文件格式
            if (file.type !== 'image/jpeg') {
                this.$message.error('上传的图片必须是jpg格式的')
                return false
            }
            // 判断文件大小
            if (file.size / 1024 / 1024 > 2) {
                this.$message.error('上传图片不能超过2m')
                return false
            }
        },
        // 封面上传成功之后调用
        coverUploadSuccess(response, file, fileList) {
            // 根据上传成功的地址，为背景图赋值
            this.courseAdd.cover = response.data.ossUrl
        },
        // 初始化当前页面
        init() {
            //根据路由判断当前是添加还是修改
            if (this.$route.params && this.$route.params.id) {
                // console.log(this.$router.params.id);
                //执行更新操作
                const courseId = this.$route.params.id
                this.getCourseAdd(courseId)
                // 获取讲师基本数据
                this.initTeacherList()
            } else {
                // 获取一级课程分类数据
                this.initSubjectList()
                // 获取讲师基本数据
                this.initTeacherList()
            }
        },
        // 添加课程基本信息
        addCourse() {
            courseApi.addCourse(this.courseAdd).then(res => {
                // 提示成功信息
                this.$message({
                    type: 'success',
                    message: '添加成功!'
                })
                // 跳转添加课程大纲页面   通过编程式路由导航的方法
                this.$router.push({ path: `/course/chapter/${res.data}` })
            })
        },
        // 更新
        updateCourse(){
            // 调用更新程序信息的api
            courseApi.updateCourse(this.courseAdd).then(res=>{
                this.$message({
                    type: "success",
                    message: "修改成功!",
                });
                //跳转至讲师列表页面，通过编程式路由
                this.$router.push({ name: "CourseChapter",params:{id:this.courseAdd.id} });
            })
        },
        getCourseAdd(id) {
            // 调用根据id获取课程基本信息的api
            courseApi.getCourseAddById(id).then(res => {
                this.courseAdd = res.data
                // 调用获取课程分类api
                subjectApi.getList().then(res=>{
                    this.subjectNestedList=res.data;
                    // 根据一级分类id获取旗下的二级分类
                    const parentSubject = this.subjectNestedList.find(
                        (item)=>item.id==this.courseAdd.subjectParentId
                    );
                    if(parentSubject){
                        this.subsubjectList=parentSubject.children
                    }
                })
            })
        }
    },

}
</script>
<style scoped>
.title {
    text-align: center;
}
</style>